package fr.upstlse.glre.server;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import fr.upstlse.glre.business.ServiceLocator;
import fr.upstlse.glre.business.service.depot.DocumentService;
import fr.upstlse.glre.business.vo.depot.DocumentVO;

public class Download extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (ServletFileUpload.isMultipartContent(req)) {
			// Create a factory for disk-based file items
			DiskFileItemFactory lDiskFileItemFactory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload lServletFileUpload = new ServletFileUpload(
					lDiskFileItemFactory);

			// Parse the request
			List<FileItem> lItems = null;
			try {
				lItems = lServletFileUpload.parseRequest(req);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			ServiceLocator serviceLocator = ServiceLocator.instance();
			DocumentService documentService = serviceLocator
					.getDocumentService();
			long lId = 0;
			
			if (lItems != null) {
				for (FileItem lFileItem : lItems) {
					if(lFileItem.isFormField()) {
						if(lFileItem.getFieldName().indexOf("documentId") != -1) {
							lId = new Long(lFileItem.getString()).longValue();
						}
					}
				}
			}

			DocumentVO lDocumentVO = documentService.getById(lId);

			resp.setContentType("application/download");
			resp.setHeader("Content-Disposition", "attachment;filename=\""
					+ lDocumentVO.getIntitule() + "\"");
			resp.setContentLength(new Long(lDocumentVO.getTaille()).intValue());

			ByteArrayInputStream lIn = new ByteArrayInputStream(lDocumentVO.getContenu());
			int bufferSize = 64 * 1024;
			OutputStream out = resp.getOutputStream();

			BufferedInputStream from = new BufferedInputStream(
					lIn, bufferSize * 2);
			byte[] bufferFile = new byte[bufferSize];
			for (int i = 0;; i++) {
				int len = from.read(bufferFile);
				if (len < 0)
					break;
				out.write(bufferFile, 0, len);
			}
			out.flush();
			
			lIn.close();

			resp.getWriter().write(lDocumentVO.getIntitule());
		}
	}
}
